package org.ouwh.fw.model.service;

import java.io.File;
import java.lang.management.ManagementFactory;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.ouwh.fw.model.ModelCore;
import org.ouwh.fw.util.Util;

public class ServiceContainer {
	private static HashMap<String, Service> services = new HashMap<String, Service>();

	public static Service getService(String id) {
		return services.get(id);
	}

	public static void startService(String id) throws Exception {
		Service service = (Service) services.get(id);
		service.start();
	}

	public static void stopService(String id) throws Exception {
		MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
		Service service = (Service) services.remove(id);
		if (service != null) {
			service.stop();
			Class<?> cl = service.getClass();
			mBeanServer.unregisterMBean(
					new ObjectName(cl.getPackage().getName() + ":name=" + cl.getSimpleName() + "[" + id + "]"));
		}
	}

	public static void loadService(String id) throws Exception {
		if (getService(id) == null) {
			Properties props = Util.loadProperties(ModelCore.getConfigPath() + File.separator + id + ".service");
			Class<?> cl = Class.forName(props.getProperty("type"));
			Service service = (Service) cl.newInstance();
			service.setId(id);
			service.setType(props.getProperty("type"));
			service.init(props);
			services.put(id, service);
			MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
			mBeanServer.registerMBean(service,
					new ObjectName(cl.getPackage().getName() + ":name=" + cl.getSimpleName() + "[" + id + "]"));
		}
	}

	public static Collection<Service> listServices() {
		return services.values();
	}
}
